package railRoad.web.slaves;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import railRoad.Passenger;
import railRoad.Route;
import railRoad.Schedule;
import railRoad.Ticket;
import railRoad.TicketType;
import railRoad.web.slaves.interfaces.ISlaveServlet;
import railRoad.worker.FactoryRW;

public class TicketServlet implements ISlaveServlet {

	public void work(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {

		Map<?, ?> parameterMap = req.getParameterMap();

		if (parameterMap.containsKey("id_route")) {

			int routeId = Integer.parseInt(req.getParameterValues("id_route")[0]);
			int passId = (Integer) req.getSession()
					.getAttribute("passanger_id");

			Route route = Schedule.getInstance().getRouteById(routeId);
			double price = route.size() * 1.25;

			Passenger passenger = new Passenger();

			Ticket ticket = new Ticket(-1, passId, routeId,
					TicketType.RESERVED.ordinal(), price);

			passenger = FactoryRW.select(passenger, passId);

			if (passenger != null) {
				boolean flag = passenger.addTicket(ticket);

				if (flag) {
					FactoryRW.update(route);
					FactoryRW.insert(ticket, 0);
				}// if flag
			}// if passenger
		}// if parameterMap
		resp.sendRedirect("/pages/history.do");

	}// work

}// TicketServlet
